# -*- coding: utf-8 -*-
# File:basepage.py
# Time: 
# Author : xingtiantian
import os
import time

import allure
import yaml
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions

from qiyeweixin.utils.log import logger


class BasePage:
    def __init__(self, driver: webdriver = None):

        if driver is None:
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
            self.driver.implicitly_wait(15)
        else:
            self.driver = driver

    def login_by_cookies(self):
        """通过 cookie 登录"""
        cookies = yaml.safe_load(open('../datas/cookies.yaml', 'r'))
        print(f"读取出来的cookie为:{cookies}")
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.refresh()

    def close_browser(self):
        """关闭浏览器"""
        self.driver.quit()

    def open_url(self, url):
        """打开url"""
        self.driver.get(url)

    def find_ele(self, by, locate=None):
        """
        查找单个元素
        :param by:定位方式
        :param locate:定位表达式
        :return:返回元素对象
        """
        try:
            if locate == None:
                ele = self.driver.find_element(*by)  # *by 解包
            else:
                ele = self.driver.find_element(by, locate)
            return ele
        except Exception as e:
            self.screen_image()  # 保存截图
            logger.info(f"元素未找到，定位方式为{by}，定位元素为{locate}，具体错误信息为{e}")

    def find_ele_click(self, by, locate=None):
        """点击单个元素"""
        self.find_ele(by, locate).click()

    def find_eles(self, by, locate=None):
        """
        查找多个元素
        :param by: 定位方式
        :param value: 定位表达式
        :return: 返回元素列表
        """
        try:
            if locate == None:
                eles = self.driver.find_elements(*by)
            else:
                eles = self.driver.find_elements(by, locate)
            return eles
        except Exception as e:
            logger.info(f"元素{by, locate}未找到，错误信息为{e}")

    def wait_locate(self, by, locate, timeout=10):
        ele = WebDriverWait(self.driver, timeout).until(expected_conditions.visibility_of_element_located((by, locate)))
        return ele

    def get_path(self, path_name):
        """
        获取绝对路径
        :param path_name: 目录名称
        :return: 目录绝对路径
        """
        # 获取当前工具文件所在的路径
        root_path = os.path.dirname(os.path.abspath(__file__))
        # 拼接当前要输出日志的路径
        dir_path = os.sep.join([root_path, '..', f'/{path_name}'])
        return dir_path

    def screen_image(self):
        """
        截图
        :return: 图片保存路径
        """
        # 截图命名
        now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
        image_name = f"{now_time}.png"
        # 拼接截图保存路径
        # windows f"{self.get_path('image')}\\{image_name}"
        image_path = f"{self.get_path('image')}/{image_name}"
        logger.info(f"截图保存路径为 {image_path}")
        # 截图
        self.driver.save_screenshot(image_path)
        allure.attach.file(image_path, name='image_name',
                           attachment_type=allure.attachment_type.PNG)  # 在allure中添加附件，展示截图
        return image_path

    def save_page_source(self):
        """
        保存页面源码
        :return: 页面源码保存路径
        """
        # 文件命名
        now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
        pagesource_name = f"{now_time}_pagesource.html"
        # 拼接文件保存路径
        # windows f"{self.get_path('pagesource')}\\{pagesource_name}"
        pagesource_path = f"{self.get_path('pagesource')}/{pagesource_name}"
        logger.info(f"页面源码文件保存路径为 {pagesource_path}")
        # 保存 page source
        with open(pagesource_path, "w", encoding="utf-8") as f:
            f.write(self.driver.page_source)
        return pagesource_path
